package reader.impl;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import com.csvreader.CsvReader;

import model.ConfigModel;
import model.ReadResultModel;
import reader.ReaderCore;

public class CSVSourceReader implements ReaderCore {

	@Override
	public Object readFile(String fileName, int subListType) throws Exception {
		String sourceFileEncodingType = (String) ConfigModel.getConfig("sourceFileEncodingType");
		CsvReader reader = new CsvReader(fileName, ',', Charset.forName(sourceFileEncodingType));
		int sublistEnnteredFlag = 0;
		String recentExpandListName = null;
		ArrayList<ArrayList<String>> tempList = null;
		
		Map<String, ArrayList<ArrayList<String>>> subListMap = new HashMap<String, ArrayList<ArrayList<String>>>();
		ArrayList<ArrayList<String>> mainList = new ArrayList<ArrayList<String>>();
	
		while (reader.readRecord()) {
			String[] colValues = reader.getValues();
			int emptyNum = 0;
			for (int i = 0; i < colValues.length; i++) {
				if (colValues[i].isEmpty())
					emptyNum++;
			}
			switch (emptyNum) {
			case 0:
			case 1:
				ArrayList<String> mainlistRecord = new ArrayList<String>();
				for (int i = 0; i < 6; i++) {
					mainlistRecord.add(colValues[i]);
				}
				mainList.add(mainlistRecord);
				break;
			case 2:
			case 3:
				if (sublistEnnteredFlag == 1) {
					tempList = new ArrayList<>();
					sublistEnnteredFlag = 0;
				}
				ArrayList<String> sublistRecord = new ArrayList<String>();
				if (0 == subListType) {
					for (int i = 0; i < 3; i++) {
						sublistRecord.add(colValues[i]);
					}
				} else {
					for (int i = 0; i < 4; i++) {
						sublistRecord.add(colValues[i]);
					}
				}
				if (tempList != null)
					tempList.add(sublistRecord);
				break;
			case 5:
				sublistEnnteredFlag = 1;
				if (tempList != null && !tempList.isEmpty()) {
					subListMap.put(recentExpandListName, tempList);
				}
				// 填充附表map的键值
				StringBuilder sBuilder = new StringBuilder();
				String readyToParse = colValues[0];
				if (readyToParse != null && readyToParse.length() > 0) {
					for (int i = 0; i < readyToParse.length(); i++) {
						if (readyToParse.charAt(i) >= 65 && readyToParse.charAt(i) <= 122) {
							sBuilder.append(readyToParse.charAt(i));
						} else {
							break;
						}
					}
				}
				recentExpandListName = sBuilder.toString();
				break;
			default:
				break;
			}
		}
		// 为最后一张附表触发添加
		if (tempList != null && !tempList.isEmpty()) {
			subListMap.put(recentExpandListName, tempList);
		}
		
		ReadResultModel resultModel = new ReadResultModel();
		resultModel.setMainList(mainList);
		resultModel.setSubListMap(subListMap);		
		return resultModel;
	}
}
